package yehang.execute;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import yehang.service.AsyncService;
import yehang.service.IPostService;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Configuration
@EnableScheduling
public class ScheduledTask {
    @Autowired
    private AsyncService asyncService;
    @Autowired
    private IPostService postService;

    /**
     * 注入这个bean才不会和websocket产生冲突
     * @return
     */
    @Bean
    public TaskScheduler taskScheduler(){
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(10);
        taskScheduler.initialize();
        return taskScheduler;
    }

    @Scheduled(fixedDelay = 1000*60*60*2)
    public void calculatePostScore(){
        List<Integer> allPostPid = postService.getALLPostPid();
        LinkedList<Integer> pids=new LinkedList<>(allPostPid);
        Integer size=allPostPid.size();
        Integer page=5;
        Integer curr=size/page;
        for (int i=0;i<5;i++){
            List<Integer> list=new ArrayList<>();
            for (int j=0;j<curr-1;j++){
                Integer remove = pids.remove(j);
                list.add(remove);
            }
            asyncService.batchUpdatePostScores(list);
        }
        List<Integer> list=new ArrayList<>();
        for (int i=0;i<pids.size();i++){
            list.add(pids.get(i));
        }
        asyncService.batchUpdatePostScores(list);
    }
}